# =============================================================================
# This Python file finds for each election the leaders that were in power just
# before and just after the election, and then tries to define an incumbent 
# party/party after the election.
# =============================================================================

import pandas as pd

import os
os.chdir("/Users/vrollet/Dropbox/Do elections matter/replication_package")

#####################################################################
### INPUT FILES 
#####################################################################

#We start by importing the list of leaders for each year
leaders = pd.read_stata('data/2_intermediary/leaders/leader_years.dta')

#As well as leader characteristics
leaders_char = pd.read_excel('data/1_input/other/leaders/party_affiliations.xlsx')
    
#Party characteristics
party_char = pd.read_excel('data/1_input/other/leaders/party_dates.xlsx')

#And election dates
pres_elections = pd.read_stata('data/3_cleaned/presidential_elections.dta')
parl_elections = pd.read_stata('data/3_cleaned/parliamentary_elections.dta')
pres_elections = pres_elections[['Country', 'Year', 'Month', 'Type_Election', 'Date']]
parl_elections = parl_elections[['Country', 'Year', 'Month', 'Type_Election', 'Date']]
elections = pd.concat([pres_elections, parl_elections])
elections.reset_index(drop=True, inplace=True)
month_to_int = {'January': "1", 'February': "2", 'March': "3", 'April': "4", 'May': "5", 'June': "6", 'July': "7", 'August': "8", 'September': "9", 'October': "10", 'November': "11", 'December': "12"}
elections['Month'] = elections['Month'].map(month_to_int)

#We replace missing values with empty strings
leaders.fillna('',inplace=True)
party_char.fillna('',inplace=True)
leaders_char.fillna('',inplace=True)
elections.fillna('',inplace=True)
elections.fillna('',inplace=True)

#####################################################################
### AUX FUNCTIONS
#####################################################################

def list_to_str(l):
    """
    This function transforms a list into a string, separating different elements
    of the list with a " // " separator
    """
    
    #If we already have a string
    if type(l)==str:
        return l
    
    #Else, if we have a list
    s=""
    for i in l:
        s+=i+" // "
    if s[-4:]==" // ":
        s=s[:-4]
    return s

def leader_data_exists(country,year,ltype):
    """
    For a country*year, this function tells whether a line of data exists 
    for the leaders of this country*year, and if the dates at which the 
    leaders took power in this country*year are available.
    The output of this function is a tuple (x,y), where x is a dummy indicating
    if there is data on the leaders in power, and y is a dummy indicating if
    there is data on the dates at which the leaders took power
    """
    
    #We only keep the line of the leader database corresponding to the request
    df=leaders[(leaders['Country']==country) & (leaders['Year']==year) & (leaders['leader_type']==ltype)]
    
    #If the line does not exist
    if df.shape[0]==0:
        return (0,0)
    
    #Else, x is set to 1 and we find the value of y
    else:
        if df["leader_start_1"].iloc[0]=="":
            return(1,0)
        else:
            return(1,1)

def find_parties(leader,country,year):
    """
    This function gives the list of parties to which a leader was affiliated
    on a given year.
    """
    
    #We check if there is data available for the leader we are interested in
    leader_char=leaders_char[(leaders_char['Country']==country)]
    leader_char=leader_char[(leader_char['Leader']==leader)]
    parties=list()
    
    #We stop here if data is unavailable, and report a missing leader in the
    #log
    if leader_char.shape[0]==0:
        return []
    
    #We retreive political affiliation
    #This information is in the variables party_name_*,party_start_*,
    #and party_end_*
    for i in range(1,10):
        
        party=str(leader_char['party_name_'+str(i)].iloc[0])
        party_id=str(leader_char['party_id_'+str(i)].iloc[0])
        party_start=str(leader_char['party_start_'+str(i)].iloc[0])
        party_end=str(leader_char['party_end_'+str(i)].iloc[0])
        
        #We only keep the parties to which the leader was affiliated at the 
        #moment of the election. If party_start_* is after the year "year" 
        #or party_end_* is before the year "year", we do not consider this
        #party affiliation
        
        #For each party affiliation, we store the start (end) year of the 
        #affiliation in the year_start (year_end) variable. Missing values are
        #coded as 0.
        
        #In the leader characteristics spreadsheet, dates are stored in the 
        #YYYY-MM-DD format.
        
        #Start year
        if party_start.lower()=="":
            year_start=0
        elif "-" in party_start:
            year_start=int(party_start.split("-")[0])
        else:
            year_start=0
            print("flag with time: "+str(party_start))
        
        #End year
        if party_end.lower()=="":
            year_end=0
        elif "-" in party_end:
            year_end=int(party_end.split("-")[0])
        else:
            year_end=0
            print("flag with time: "+str(party_end))
        
        #There are four possible cases in which we consider the party affiliation
        #as is valid for the year "year"
        if party!="":
            #Case 1: we do not know when party affiliation started or ended
            if year_start==0 and year_end==0:
                parties.append((party,party_id))
            #Case 2: we only know the year at which the party affiliation ended,
            #and year_end is the year "year", or after
            elif year_start==0 and year_end!=0:
                if year<=year_end:
                    parties.append((party,party_id))
            #Case 3: we only know the year at which the party affiliation started,
            #and year_start is the year "year", or before
            elif year_start!=0 and year_end==0:
                if year>=year_start:
                    parties.append((party,party_id))
            #Case 4: we know both the start and end year of the affiliation, and
            #the year "year" is (weakly) between year_start and 
            #year_end
            else :
                if year>=year_start and year<=year_end:
                    parties.append((party,party_id))
    
    #If no parties were found after this step, then we return an empty list
    if parties==[]:
        return parties
    
    #We eliminate parties that were dissolved before the year "year" or created
    #after the year "year"
    
    res=[]
    for elt in parties: 
        party_name=elt[0]
        party_id=elt[1]
        #We find the party in the party characteristics database
        pchar=party_char[(party_char['wikidata_id']==party_id)]

        #If the party is not in the dataframe, we report a missing party and 
        #consider the party existed at the moment of the election.
        if pchar.shape[0]==0:
            res.append(party_name)
        
        #Else, we have data and check whether the party existed during year "year"
        else:
            inception=str(pchar['inception'].iloc[0]).split("-")[0]
            dissolved=str(pchar['dissolved'].iloc[0]).split("-")[0]
            #We code missing inception and dissolution dates as 0
            if inception=="":
                inception=0
            else:
                inception=int(inception)
            if dissolved=="":
                dissolved=0
            else:
                dissolved=int(dissolved)
            
            #There are four possible cases in which we consider the party affiliation
            #as is valid for the year "year"

            #Case 1: we do not know when party started or ended activity
            if inception==0 and dissolved==0:
                res.append(party_name)
            #Case 2: we only know the year at which the party was dissolved,
            #and this year is is the year "year", or after
            elif inception==0 and dissolved!=0:
                if year<=dissolved:
                    res.append(party_name)
            #Case 3: we only know the inception year,
            #and inception is the year "year", or before
            elif inception!=0 and dissolved==0:
                if year>=inception:
                    res.append(party_name)
            #Case 4: we know both the inception and dissolution years, and
            #the year "year" is (weakly) between inception and dissolved
            else :
                if year>=inception and year<=dissolved:
                    res.append(party_name)
    return res

def find_leaders_plusminus(date,year,country,ltype,minusdays,plusdays):
    """
    This function gives the list of leaders that were in power as ltype during 
    the period between date-minusdays and date+plusdays, and the duration of 
    their power during this (plus+minus)-day period.
    The argument "date" will be the date of an election.
    Note that minusdays and plusdays can be negative, allowing for periods 
    which do not contain the date "date". 
    The arguments minusdays and plusdays will be set to capture either the 
    two-year period immediately after the election or the two-year period
    immediately before the election.
    """
    
    #Leaders in the period of interest are stored with their start dates here
    #They are stored in the order in which they gained power
    leaders_list=list()
    
    ##We start by gathering data for the years surrounding the election
            
    #We gather data for election year
    
    election_year_leaders=leaders[(leaders['Country']==country) & (leaders['Year']==year) & (leaders['leader_type']==ltype)]
    if election_year_leaders.shape[0]==0:
        print("   No data for leaders of "+country+" "+str(year))
        return ["flag: no data for election year",0]
    
    if minusdays>367:
        #We gather data for the year before the year before the election
        pre_pre_election_year_leaders=leaders[(leaders['Country']==country) & (leaders['Year']==year-2) & (leaders['leader_type']==ltype)]
        if pre_pre_election_year_leaders.shape[0]==0:
            print("   No data for leaders of "+country+" "+str(year-2))         
            return ["flag: no data for pre-pre-election year",0]
        for i in range(1,11):
            l=pre_pre_election_year_leaders['leader_'+str(i)].iloc[0]
            ld=pre_pre_election_year_leaders['leader_start_'+str(i)].iloc[0]
            if str(l)!="":
                 leaders_list.append([l,ld])
    
    if minusdays>0:   
        #We gather data for the year before the election
        pre_election_year_leaders=leaders[(leaders['Country']==country) & (leaders['Year']==year-1) & (leaders['leader_type']==ltype)]
        if pre_election_year_leaders.shape[0]==0:
            print("   No data for leaders of "+country+" "+str(year-1))
            return ["flag: no data for pre-election year",0]
        for i in range(1,11):
            l=pre_election_year_leaders['leader_'+str(i)].iloc[0]
            ld=pre_election_year_leaders['leader_start_'+str(i)].iloc[0]
            if str(l)!="":
                leaders_list.append([l,ld])
                
    for i in range(1,11):
        l=election_year_leaders['leader_'+str(i)].iloc[0]
        ld=election_year_leaders['leader_start_'+str(i)].iloc[0]
        if str(l)!="":
             leaders_list.append([l,ld])
    
    if plusdays>0:   
        #We gather data for the year after the election
        post_election_year_leaders=leaders[(leaders['Country']==country) & (leaders['Year']==year+1) & (leaders['leader_type']==ltype)]
        if post_election_year_leaders.shape[0]==0:
            print("   No data for leaders of "+country+" "+str(year+1))
            return ["flag: no data for post-election year",0]
        for i in range(1,11):
            l=post_election_year_leaders['leader_'+str(i)].iloc[0]
            ld=post_election_year_leaders['leader_start_'+str(i)].iloc[0]
            if str(l)!="":
                leaders_list.append([l,ld])
    
    if plusdays>367:   
        #We gather data for the year after the year after the election
        post_post_election_year_leaders=leaders[(leaders['Country']==country) & (leaders['Year']==year+2) & (leaders['leader_type']==ltype)]
        if post_post_election_year_leaders.shape[0]==0:
            print("  No data for leaders of "+country+" "+str(year+2))          
            return ["flag: no data for post-post-election year",0]
        for i in range(1,11):
            l=post_post_election_year_leaders['leader_'+str(i)].iloc[0]
            ld=post_post_election_year_leaders['leader_start_'+str(i)].iloc[0]
            if str(l).lower()!="":
                leaders_list.append([l,ld])
        
    #We clean the leader list (leaders that span several years are shown twice)

    leaders_list_temp=[]
    current_leader=""
    for element in leaders_list:
        leadername=element[0]
        if leadername!=current_leader:                                 
            leaders_list_temp.append(element)
            current_leader=leadername
    leaders_list=leaders_list_temp

    #We check that we have dates of power start for all leaders of interest
    for i in range(len(leaders_list_temp)):
        if str(leaders_list_temp[i][1])=="":
            print("   No data for leaders start time for election: "+country+" "+str(year))
            return ["flag: no data on leader start times",0]
    
    #We define a list with the name of the leaders in power during the time period of 
    #interest, and the number of days between the election and the date of beginning 
    #of power of the leader (in relative terms)
    
    leaders_in_period=list()
    
    for elt in leaders_list:
        leadername=elt[0]
        leaderstart=elt[1]
        time_before_election=(date-leaderstart).days                  
        leaders_in_period.append([leadername,time_before_election])
    
    #We keep only leaders that were in power during the relevant time period
    days_list=[i[1] for i in leaders_in_period]
    before=[i for i in days_list if i>minusdays]
    after=[i for i in days_list if i<-plusdays]
    while len(before)>1:
        leaders_in_period.pop(0)
        days_list=[i[1] for i in leaders_in_period]
        before=[i for i in days_list if i>minusdays]
    while len(after)>1:
        leaders_in_period.pop(len(leaders_in_period)-1)
        days_list=[i[1] for i in leaders_in_period]
        after=[i for i in days_list if i<-plusdays]
    
    if len(leaders_in_period)==0:
        return ["flag: not enough data on leaders",0]
    
    if leaders_in_period[0][1]>=minusdays:
        leaders_in_period[0][1]=minusdays
    if leaders_in_period[-1][1]<=-plusdays:
        leaders_in_period[-1][1]=-plusdays
    
    #We define a new list with the leaders in power during the period and the number
    #of days they were in power during this period
    
    #There is a special case in which there was only one leader during the period of
    #interest
    if len(leaders_in_period)==1:
        return [[leaders_in_period[0][0],plusdays+minusdays]]          
        
    #For all the other cases:
    result=list()
    compteur=-plusdays
    for i in range(1,1+len(leaders_in_period)):
        current=leaders_in_period[-i]
        current_leader=current[0]
        current_time=current[1]
        nb_days=current_time-compteur
        if nb_days>0:
            result.append([current_leader,nb_days])
        compteur=current_time
    
    return result

def find_parties_plusminus(date,year,country,ltype,minusdays,plusdays):
    #This function gives the list of parties that were in power during the period between
    #date-minusdays and date+plusdays, and the duration of their power during this 
    #(plus+minus)-day period 
    #date is the date of an election
    leader_list=find_leaders_plusminus(date,year,country,ltype,minusdays,plusdays)
    
    parties=dict()
    
    #print(leader_list)
    
    #Case of an empty list:
    if len(leader_list)==0:
        return parties
    
    #Case of an flag list:
    if "flag:" in leader_list[0]:
        return parties
    
    print("  * Leaders (730 days)\n")
    for element in leader_list:
        leader=element[0]
        nb_days=element[1]
        parties_in_power=find_parties(leader,country,year)
        str_parties=list_to_str(parties_in_power)
        if len(str_parties)>1:
            print("\t- "+leader+" ("+str(nb_days)+" days in power) - "+str_parties)
        else:
            print("\t- "+leader+" ("+str(nb_days)+" days in power) - Unknown party")
        for party in parties_in_power:
            if party in parties:
                parties[party]+=nb_days
            else:
                parties[party]=nb_days
    
    print("\n  * Parties (730 days)\n")
    for party in parties:
        if parties[party]>0:
            if party=="" :
                print("\t- Unknown party: "+str(parties[party])+" days")
            else:
                print("\t- "+party+": "+str(parties[party])+" days")
    
    return parties

def find_leaders_yearbefore(year,country,ltype):
    #This function gives the list of leaders that were in power the year before the
    #election
    leaders_list=list()
    pre_election_year_leaders=leaders[(leaders['Country']==country) & (leaders['Year']==year-1) & (leaders['leader_type']==ltype)]
    if pre_election_year_leaders.shape[0]==0:
        print("No data for leaders of "+country+" "+str(year-1))
        return ["flag: no data for pre-election year",0]
    for i in range(1,11):
        l=pre_election_year_leaders['leader_'+str(i)].iloc[0]
        if str(l).lower()!="":
            leaders_list.append(l)
    return leaders_list

def find_leaders_yearafter(year,country,ltype):
    #This function gives the list of leaders that were in power the year before the
    #election
       
    leaders_list=list()
    post_election_year_leaders=leaders[(leaders['Country']==country)]
    post_election_year_leaders=post_election_year_leaders[(post_election_year_leaders['Year']==year+1)]
    post_election_year_leaders=post_election_year_leaders[(post_election_year_leaders['leader_type']==ltype)]
    if post_election_year_leaders.shape[0]==0:
        print("No data for leaders of "+country+" "+str(year+1))
        return ["flag: no data for post-election year",0]
    for i in range(1,11):
        l=post_election_year_leaders['leader_'+str(i)].iloc[0]
        if str(l).lower()!="":
            leaders_list.append(l)
    return leaders_list

def find_parties_yearbefore(year,country,ltype):
    #This function lists the parties of the leaders that 
    parties=dict()
    leaders_list=find_leaders_yearbefore(year,country,ltype)
    nb_leaders=len(leaders_list)
    if nb_leaders!=0:
        print("  * Leaders (year before)\n")
    for l in leaders_list:
        lparties=find_parties(l,country,year)
        print("\t- "+l+": "+list_to_str(lparties))
        for party in lparties:
            if party in parties:
                parties[party]+=1
            else:
                parties[party]=1     
    return (nb_leaders, parties)

def find_parties_yearafter(year,country,ltype):
    #This function lists the parties of the leaders that 
    parties=dict()
    leaders_list=find_leaders_yearafter(year,country,ltype)
    nb_leaders=len(leaders_list)
    if nb_leaders!=0:
        print("  * Leaders (year after)\n")
    for l in leaders_list:
        lparties=find_parties(l,country,year)
        print("\t- "+l+": "+list_to_str(lparties))
        for party in lparties:
            if party in parties:
                parties[party]+=1
            else:
                parties[party]=1
    return (nb_leaders, parties)

def find_leader_over_a_year(d):
    #From a dictionary which associates leaders to times in power, returns a leader if one 
    #was in power for over 365 days
    
    #Case if we have an flag return or an empty list
    if type(d)==list:
        if len(d)==0:
            return ""
        if "flag" in d[0]:
            return ""
        
    #Case where the entry is a list
    if type(d)!=dict:
        d2=dict()
        for i in d:
            if i[0] in d2:
                d2[i[0]]+=i[1]
            else:
                d2[i[0]]=i[1]
        d=d2
   
    for leader in d:
        if d[leader]>=365:
            return leader
    return ""

def find_parties_over_a_year(d):
    #From a dictionary which associates leaders to times in power, returns a leader if one 
    #was in power for over 365 days. If several parties meet this definition, we return the list of 
    #parties that hit the max duration of power
    
    #Case where the entry is a list
    if type(d)!=dict:
        d2=dict()
        for i in d:
            d2[i[0]]=i[1]
        d=d2
        
    maxtime=0
    res=[]
    for party in d:
        if d[party]>=365:
            if d[party]==maxtime:
                res.append(party)
            else:
                maxtime=d[party]
                res=[party]
    if res==[]:
        return ""
    else:
        return list_to_str(res)

def find_incumbent_leader(date,year,country,ltype):
    
    #This function finds the incumbent leader according to the definition
    #in our methodology
    #Returns also the method used:
    #   method 1: with the days
    #   method 2: using the year before the election
    
    #If we do not know the date of the election, we have date==""
    #We check the availability of the date of the election
    if str(date)=="NaT":
        eldatav=0
    else:
        eldatav=1
    
    #Checking data availability  
    
    
    datav=leader_data_exists(country,year,ltype)
    datavpre=leader_data_exists(country,year-1,ltype)
    
    #If we know the date at which the election took place
    if eldatav==1:
        #If we have data on the leaders that were in power the year of the
        #election and the year before (with dates of accession to power)
        #We check the leaders in power during the -730 days                  
        if datav==(1,1) and datavpre==(1,1):
            leaders_365=find_leaders_plusminus(date,year,country,ltype,731,-1)
            #If a leader was in power for over 365 days
            found = find_leader_over_a_year(leaders_365)
            if found!="":
                return (found,1)
    
    #If data is missing at steps above, we try looking at the years before the election
    else:
        if datavpre[0]==1:
            leader_list=find_leaders_yearbefore(year,country,ltype)
            if len(leader_list)==1:
                return (leader_list[0],2)
    #If everything above failed, we cannot define an incumbent leader
    return ""


def find_incumbent_party(date,year,country,ltype):
    #This function finds the incumbent party according to the definition
    #in our methodology
    #Returns also the method used:
    #   method 1: with the days 
    #   method 2: using the year before the election   
    
    #First, we check if we can define an incumbent leader
    incumbent_leader=find_incumbent_leader(date,year,country,ltype)
    if incumbent_leader!="":
        incumbent_leader=incumbent_leader[0]
        if incumbent_leader!="" and not("flag" in incumbent_leader):
            parties=find_parties(incumbent_leader,country,year)
            parties_str=list_to_str(parties)
            if parties_str=="":
                parties_str="Unknown party"
            print ("Incumbent leader found: "+incumbent_leader+" ("+parties_str+")")
            return parties_str
    
    #Else, we look at data availability 
    if str(date)=="NaT":
        eldatav=0
    else:
        eldatav=1
    datav=leader_data_exists(country,year,ltype)
    datavpre=leader_data_exists(country,year-1,ltype)
    
    #If we know the date at which the election took place
    if eldatav==1:
        #If we have data on the leaders that were in power the year of the
        #election and the year before (with dates of accession to power)
        #We check the leaders in power during the -730 days                                
        if datav==(1,1) and datavpre==(1,1):
            parties_365=find_parties_plusminus(date,year,country,ltype,731,-1)
            return (find_parties_over_a_year(parties_365),1)
        else:                                                               
            return ""
        
    #If data is missing at steps above, we try looking at the years before the election
    else:
        if datavpre[0]==1:
            parties_list=find_parties_yearbefore(year,country,ltype)
            if len(parties_list)==1:
                return (parties_list[0],2)
        
    #If everything above failed, we cannot define an incumbent party
    return ""

def find_leader_after_election(date,year,country,ltype):
    
    #This function finds the leader after the election according to the definition
    #in our methodology
    #Returns also the method used:
    #   method 1: with the days
    #   method 2: using the year before the election
    
    #If we do not know the date of the election, we have date==""
    #We check the availability of the date of the election
    if str(date)=="NaT":
        eldatav=0
    else:
        eldatav=1
    
    #Checking data availability
        
    datav=leader_data_exists(country,year,ltype)
    datavpost=leader_data_exists(country,year+1,ltype)
    
    #If we know the date at which the election took place
    if eldatav==1:
        #If we have data on the leaders that were in power the year of the
        #election and the year after (with dates of accession to power)
        #We check the leaders in power during the +730 days                    
        if datav==(1,1) and datavpost==(1,1):
            leaders_365=find_leaders_plusminus(date,year,country,ltype,0,730)
            #If a leader was in power for over 365 days
            found = find_leader_over_a_year(leaders_365)
            if found!="":
                return (found,1)
    
    #If data is missing at steps above, we try looking at the years before the election
    else:
        if datavpost[0]==1:
            leader_list=find_leaders_yearafter(year,country,ltype)
            if len(leader_list)==1:
                return (leader_list[0],2)
    #If everything above failed, we cannot define an incumbent leader
    return ""


def find_party_after_election(date,year,country,ltype):
    #This function finds the party after the election according to the definition
    #in our methodology
    #Returns also the method used:
    #   method 1: with the days 
    #   method 2: using the year after the election   
    
    #First, we check if we can define an leader after the election
    leader_after=find_leader_after_election(date,year,country,ltype)
    if leader_after!="":
        leader_after=leader_after[0]
        if leader_after!="" and not("flag" in leader_after):
            parties=find_parties(leader_after,country,year)
            parties_str=list_to_str(parties)
            if parties_str=="":
                parties_str="Unknown party"
            print ("Leader after the election found: "+leader_after+" ("+parties_str+")")
            return list_to_str(parties)
    
    #Else, we look at data availability 
    if str(date)=="NaT":
        eldatav=0
    else:
        eldatav=1
    datav=leader_data_exists(country,year,ltype)
    datavpost=leader_data_exists(country,year+1,ltype)
    
    #If we know the date at which the election took place
    if eldatav==1:
        #If we have data on the leaders that were in power the year of the
        #election and the year before (with dates of accession to power)
        #We check the leaders in power during the -730 days                   
        if datav==(1,1) and datavpost==(1,1):
            parties_365=find_parties_plusminus(date,year,country,ltype,0,730)
            return (find_parties_over_a_year(parties_365),1)
        
    #If data is missing at steps above, we try looking at the years before the election
    else:
        if datavpost[0]==1:
            parties_list=find_parties_yearafter(year,country,ltype)
            if len(parties_list)==1:
                return (parties_list[0],2)
        
    #If everything above failed, we cannot define an incumbent party
    return ""

     
#####################################################################
### DEFINING VARIABLES 
#####################################################################

elections['incumbent_leader_HOS']=""
elections['incumbent_party_HOS']=""
elections['leader_after_HOS']=""
elections['party_after_HOS']=""
elections['incumbent_leader_HOG']=""
elections['incumbent_party_HOG']=""
elections['leader_after_HOG']=""
elections['party_after_HOG']=""

#Looping over all elections in the database, and every leader type
for index, row in elections.iterrows():
    for ltype in ["HOS","HOG"]:
        
        incumbent_leader=""
        incumbent_party=""
        leader_after=""
        party_after=""
        
        country=row['Country']
        year=row['Year']
        date=row['Date']
        eltype=row['Type_Election']

        
        print("\n----------------------------------------------------")
        print("### "+country+"/"+eltype+"/"+str(year)+"/"+ltype)
        print("----------------------------------------------------\n")
        
        #Displaying the date of the election
        if str(date)!="NaT":
            print("# Date of the election: "+str(date).split(" ")[0]+"\n")
        else:
            print("# Unknown election date\n")
                  
                  
        #Before the election
           
        print("# Incumbent\n")
        
        
        incumbent_leader=find_incumbent_leader(date,year,country,ltype)
        if len(incumbent_leader)==2:
            incumbent_leader=incumbent_leader[0]
        
        incumbent_party=find_incumbent_party(date,year,country,ltype)
        if len(incumbent_party)==2 :
            incumbent_party=incumbent_party[0]
        
        if incumbent_leader!="":
            print("\t- incumbent: "+ incumbent_leader)
        else:
            print("\t- incumbent not found")
        
        if incumbent_party!="":
            print("\t- incumbent party: "+ incumbent_party)
        else:
            print("\t- incumbent party not found")
            
        #After the election
            
        print("\n# After the election\n")
                
        leader_after=find_leader_after_election(date,year,country,ltype)
        if len(leader_after)==2:
            leader_after=leader_after[0]
        
        party_after=find_party_after_election(date,year,country,ltype)
        if len(party_after)==2 :
            party_after=party_after[0]
        
        if leader_after!="":
            print("\t- leader after the election: "+ leader_after)
        else:
            print("\t- leader after the election not found")
        
        if party_after!="":
            print("\t- party after the election: "+ party_after)
        else:
            print("\t- party after the election not found")
            
        
        #Additional output (comment out if necessary)
        if str(date)!="":
            print("\n-- NOTES --\n")
            
            print("\t -- Before the election\n")
            find_parties_plusminus(date,year,country,ltype,731,-1)
            print("\n\t -- After the election\n")
            find_parties_plusminus(date,year,country,ltype,0,730)
        
        if incumbent_party=="Unknown party":
            incumbent_party = ""
        if party_after=="Unknown party":
            party_after = ""
        elections.at[index, 'incumbent_leader_'+ltype] = incumbent_leader
        elections.at[index, 'incumbent_party_'+ltype] = incumbent_party
        elections.at[index, 'leader_after_'+ltype] = leader_after
        elections.at[index, 'party_after_'+ltype] = party_after
        
elections = elections.drop(columns=['Date'])
elections.to_excel('data/2_intermediary/leaders/leaders_before_after.xlsx', index=False)
